<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>递归深入</title>
</head>

<body>
  <script>
    // 试输出斐波那契数列：[1,1,2,3,5,8,13,21,34,55]

    // 创建一个函数功能是返回下列为n的这项的数字
    var num1 = 0
    function fib1(n) {
      num1 += 1
      return n === 0 || n === 1 ? 1 : fib1(n - 1) + fib1(n - 2)
    }
    console.log(fib1(5))
    console.log('函数执行次数为' + num1)

    // 优化函数：加入缓存
    var cache = {}
    var num = 0
    function fib(n) {
      if (cache.hasOwnProperty(n)) {
        return cache[n]
      } else {
        num += 1
        var v = n == 0 || n == 1 ? 1 : fib(n - 1) + fib(n - 2)
        cache[n] = v
        return v
      }
    }
    console.log(fib(5))
    console.log('函数执行次数为' + num)
  </script>
</body>

</html>